package com.atugigu.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ：HB
 * @date ：Created in 2020/10/30 1:02
 * @description：自定义拦截器
 *  自定义拦截器
 *  1. 创建拦截器类实现HandlerInterceptor[处理拦截器]接口
 *  2. 配置拦截器  <mvc:interceptors>
 *  3. 测试拦截器的拦截效果
 */
public class MyInterceptor1 implements HandlerInterceptor {
    /**
     * 再目标方法执行之前执行
     * @param request
     * @param response
     * @param handler
     * @return:返回true代表放行,返回false代表不放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("preHandle...");

        //拦截器中可以执行这种业务逻辑
        /**
         * 如果请求参数中有参数:param=yes 才放行,否则不放行
         */
        String parameter = request.getParameter("param");
        if ("yes".equals(parameter)){
            return true;
        }else {
            request.getRequestDispatcher("/error.jsp").forward(request,response);
            return false;
        }
    }

    /**
     *在目标方法执行之后,视图对象返回之前执行.
     * 这个方法的作用可以对modelandview进行修改
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        modelAndView.addObject("name","postHandle...修改modelAndView");
        System.out.println("postHandle...");

    }

    /**
     *视图返回之后执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}
